/**
 * VUEX管理页面, 具体思维逻辑可参考: 
 */
import router from "./router";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth";
import { isHttp } from "@/utils/validate";
import { isRelogin } from "@/utils/request";
import useUserStore from "@/store/modules/user";
import useSettingsStore from "@/store/modules/settings";
import usePermissionStore from "@/store/modules/permission";
import { env } from "process";

NProgress.configure({ showSpinner: false });

// 白名单
const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];

// 默认首页路径
const indexPath:string = import.meta.env.VITE_APP_INDEX_PATH || '';


let rootToken: string = ""; //记录统一登录入口使用的token, 防止重复login操作

router.beforeEach((to: any, from, next) => {
	NProgress.start();

	const block = () => {
		to.meta.title && useSettingsStore().setTitle(to.meta.title);
		if (to.path === "/login") {
			// 不能进入登录页面, 默认进入首页
			next({ path: indexPath });
			NProgress.done();
		} else {
			if (useUserStore().roles.length === 0) {
				isRelogin.show = true;
				// 判断当前用户是否已拉取完user_info信息
				// prettier-ignore
				useUserStore().getInfo().then(() => {
							isRelogin.show = false;
							// prettier-ignore
							usePermissionStore().generateRoutes().then((accessRoutes: any) => {
								// roles权限生成可访问的路由表
								accessRoutes.forEach((route: any) => {
									if (!isHttp(route.path)) {
										 // 动态添加可访问路由表
										router.addRoute(route);
									}
								});
								
								//清除链接中多余的参数
								var params = { ...to, replace: true }

								if(params.query.token) delete params.query.token
								if(params.query.rootUrl) delete params.query.rootUrl
								
								if(to.path == '/') {
									params.path = indexPath
									params.query = {}
								}
								// hack方法 确保addRoutes已完成
								next(params);
							});
						})
						.catch(async err => {
							await useUserStore().logOut().then(() => {
								ElMessage.error(err);
								next({ path: "/" });
							});
						});
			} else {
				next();
			}
		}
	};

	let query = to.query || {};
	// 如果浏览器中出现了token参数且没有被记录过
	if (query.token) {
		if (rootToken != query.token) {
			rootToken = query.token;
			//如果有token,而且没有被记录, 则记录并登录用户
			useUserStore()
				.userTokenLogin(query.token)
				.then(() => {
					block();
				});
		} else {
			block();
		}
	} else {
		if (rootToken || whiteList.indexOf(to.path) !== -1) {
			// 在免登录白名单，直接进入
			next();
		} else {
			next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
